package service

import (
	"go_web_todo/dao"
	"go_web_todo/models"
	"go_web_todo/pkg/e"
	"go_web_todo/pkg/utils"
	"go_web_todo/serializer"

	logging "github.com/sirupsen/logrus"
)

// 用户服务
type UserService struct {
	UserName string `form:"user_name" json:"user_name" binding:"required,min=3,max=15" example:"FanOne"`
	Password string `form:"password" json:"password" binding:"required,min=5,max=16" example:"FanOne666"`
}

//用户注册
func (service *UserService) UserRegisterService() *serializer.Response {
	var user models.User
	code := e.SUCCESS
	dao.FindUserByName(service.UserName, &user)
	if user != (models.User{}) {
		code = e.ErrorExistUser
		return &serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
		}
	}
	user.UserName = service.UserName
	if err := user.SetPassword(service.Password); err != nil { //密码加密
		logging.Info(err)
		code = e.ErrorDatabase
		return &serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
		}
	}
	if err := dao.UserRegister(&user); err != nil {
		logging.Info(err)
		code = e.ErrorDatabase
		return &serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
		}
	}
	return &serializer.Response{
		Status: code,
		Msg:    e.GetMsg(code),
	}
}

//用户登录
func (service *UserService) Login() serializer.Response {
	var user models.User
	code := e.SUCCESS
	if err := dao.FindUserByName(service.UserName, &user); err != nil {
		if user == (models.User{}) { //查询为空，说明用户不存在
			logging.Info(err)
			code = e.ErrorNotExistUser
			return serializer.Response{
				Status: code,
				Msg:    e.GetMsg(code),
			}
		}
	}
	if user.CheckPassword(service.Password) == false {
		code = e.ErrorNotCompare
		return serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
		}
	}
	// 同一用户签发第二次token之后，第一次token应该失效问题，考虑将token放到Redis中，第二次登录就可以检查是否签发过
	token, err := utils.GenerateToken(user.ID, service.UserName, 0)
	if err != nil {
		logging.Info(err)
		code = e.ErrorAuthToken
		return serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
		}
	}
	return serializer.Response{
		Status: code,
		Data:   serializer.TokenData{User: serializer.BuildUser(user), Token: token},
		Msg:    e.GetMsg(code),
	}
}
